using CoreManager.API.Common;
using CoreManager.Models.DTOs;
using CoreManager.Services.Files;
using Microsoft.AspNetCore.Mvc;

namespace CoreManager.API.Controllers
{
    /// <summary>
    /// 文件管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class FileController : BaseController
    {
        private readonly IFileService _fileService;
        private readonly ILogger<FileController> _logger;

        public FileController(
            IFileService fileService,
            ILogger<FileController> logger) : base(logger)
        {
            _fileService = fileService;
            _logger = logger;
        }

        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="businessType">业务类型</param>
        /// <param name="businessId">业务ID</param>
        /// <returns></returns>
        [HttpPost("upload")]
        [RequestSizeLimit(10 * 1024 * 1024)] // 10MB
        public async Task<IActionResult> UploadFile(
            IFormFile file,
            [FromForm] string? businessType = null,
            [FromForm] string? businessId = null)
        {
            try
            {
                if (file == null)
                {
                    return BadRequest("请选择要上传的文件");
                }

                var uploadDto = new FileUploadDto
                {
                    BusinessType = businessType,
                    BusinessId = businessId
                };

                var result = await _fileService.UploadFileAsync(file, uploadDto);
                
                if (result.Code == 200)
                {
                    return Success(result.Data, result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, "上传文件");
            }
        }

        /// <summary>
        /// 上传多个文件
        /// </summary>
        /// <param name="files">文件列表</param>
        /// <param name="businessType">业务类型</param>
        /// <param name="businessId">业务ID</param>
        /// <returns></returns>
        [HttpPost("upload-multiple")]
        [RequestSizeLimit(50 * 1024 * 1024)] // 50MB
        public async Task<IActionResult> UploadFiles(
            IFormFileCollection files,
            [FromForm] string? businessType = null,
            [FromForm] string? businessId = null)
        {
            try
            {
                if (files == null || files.Count == 0)
                {
                    return BadRequest("请选择要上传的文件");
                }

                var uploadDto = new FileUploadDto
                {
                    BusinessType = businessType,
                    BusinessId = businessId
                };

                var result = await _fileService.UploadFilesAsync(files, uploadDto);
                
                if (result.Code == 200)
                {
                    return Success(result.Data, result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, "批量上传文件");
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="deleteDto">删除请求</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleteFile([FromBody] FileDeleteDto deleteDto)
        {
            try
            {
                var result = await _fileService.DeleteFileAsync(deleteDto.RelativePath);
                
                if (result.Code == 200)
                {
                    return Success(result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, "删除文件");
            }
        }

        /// <summary>
        /// 批量删除文件
        /// </summary>
        /// <param name="batchDeleteDto">批量删除请求</param>
        /// <returns></returns>
        [HttpDelete("batch")]
        public async Task<IActionResult> BatchDeleteFiles([FromBody] BatchFileDeleteDto batchDeleteDto)
        {
            try
            {
                var result = await _fileService.BatchDeleteFilesAsync(batchDeleteDto.RelativePaths);
                
                if (result.Code == 200)
                {
                    return Success(result.Message);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, "批量删除文件");
            }
        }

        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="relativePath">文件相对路径</param>
        /// <returns></returns>
        [HttpGet("info")]
        public async Task<IActionResult> GetFileInfo([FromQuery] string relativePath)
        {
            try
            {
                var result = await _fileService.GetFileInfoAsync(relativePath);
                
                if (result.Code == 200)
                {
                    return Success(result.Data);
                }
                
                return Fail(result.Message, result.Code);
            }
            catch (Exception ex)
            {
                return HandleException(ex, "获取文件信息");
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="relativePath">文件相对路径</param>
        /// <returns></returns>
        [HttpGet("download")]
        public async Task<IActionResult> DownloadFile([FromQuery] string relativePath)
        {
            try
            {
                var (stream, contentType, fileName) = await _fileService.GetFileStreamAsync(relativePath);
                
                if (stream == null)
                {
                    return NotFound("文件不存在");
                }

                return File(stream, contentType, fileName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "下载文件失败: {RelativePath}", relativePath);
                return HandleException(ex, "下载文件");
            }
        }

        /// <summary>
        /// 预览文件（在浏览器中直接显示）
        /// </summary>
        /// <param name="relativePath">文件相对路径</param>
        /// <returns></returns>
        [HttpGet("preview")]
        public async Task<IActionResult> PreviewFile([FromQuery] string relativePath)
        {
            try
            {
                var (stream, contentType, fileName) = await _fileService.GetFileStreamAsync(relativePath);
                
                if (stream == null)
                {
                    return NotFound("文件不存在");
                }

                // 设置为inline，浏览器会尝试显示而不是下载
                return File(stream, contentType);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "预览文件失败: {RelativePath}", relativePath);
                return HandleException(ex, "预览文件");
            }
        }
    }
}


